<?php

class Ext_Fastdfs_Upload
{
    protected static $_instance = null;
    
    protected $_tracker;
    protected $_storage;
    
    const RENAME_IMAGE_FAILED = 'renameImageFailed';
    protected $_messageTemplates = array(
        self::RENAME_IMAGE_FAILED => "Rename image failed.",
    );
    protected $_messager;
    
    public static function getInstance()
    {
        $_className = _get_called_class();
        if (!isset(self::$_instance[$_className])) {
            self::$_instance[$_className] = new $_className();
        }

        return self::$_instance[$_className];
    }
    
    protected function __construct()
    {
        $this->_messager = new Ext_Messager($this->_messageTemplates);
        
        $tracker = fastdfs_tracker_get_connection();
        
        if (!fastdfs_active_test($tracker))
        {
            require_once 'Ext/Fastdfs/Exception.php';
            throw new Ext_Fastdfs_Exception("Fastdfs errno: " . fastdfs_get_last_error_no() . ", Fastdfs error: " . fastdfs_get_last_error_info());
        }
        $server = fastdfs_connect_server($tracker['ip_addr'], $tracker['port']); 
        $storage = fastdfs_tracker_query_storage_store();
        if (!$storage)
        {
            require_once 'Ext/Fastdfs/Exception.php';
            throw new Ext_Fastdfs_Exception("Fastdfs errno: " . fastdfs_get_last_error_no() . ", Fastdfs error: " . fastdfs_get_last_error_info());
        }
        
        $server = fastdfs_connect_server($storage['ip_addr'], $storage['port']);
        if (!$server)
        {
            require_once 'Ext/Fastdfs/Exception.php';
            throw new Ext_Fastdfs_Exception("Fastdfs errno: " . fastdfs_get_last_error_no() . ", Fastdfs error: " . fastdfs_get_last_error_info());
        }
        
        if (!fastdfs_active_test($server))
        {
            require_once 'Ext/Fastdfs/Exception.php';
            throw new Ext_Fastdfs_Exception("Fastdfs errno: " . fastdfs_get_last_error_no() . ", Fastdfs error: " . fastdfs_get_last_error_info());
        }
        
        $storage['sock'] = $server['sock'];
        
        $this->_tracker = $tracker;
        $this->_storage = $storage;
    }

    public function upload($file)
    {
        $file_info = fastdfs_storage_upload_by_filename($file, null, array(), null, $this->_tracker, $this->_storage);
        if(!$file_info){
            require_once 'Ext/Fastdfs/Exception.php';
            throw new Ext_Fastdfs_Exception("Fastdfs errno: " . fastdfs_get_last_error_no() . ", Fastdfs error: " . fastdfs_get_last_error_info());
        }
        
        return $file_info;
    }
}
